package com.sdkj.dspservice.common.utils.okhttp3;

import com.sdkj.dspservice.common.base.entity.BaseResult;
import com.sdkj.dspservice.common.constant.HttpStatus;
import com.sdkj.dspservice.common.utils.StringUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by qhong on 2018/7/3 16:55
 *
 * @author tm
 **/
public class OkHttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtils.class);

    /**
     * 根据map获取get请求参数
     *
     * @param queries
     * @return
     */
    public static StringBuffer getQueryString(String url, Map<String, String> queries) {
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        return sb;
    }

    /**
     * 调用okhttp的newCall方法
     *
     * @param request
     * @return
     */
    private static BaseResult execNewCall(Request request) {
        System.out.println("**********************response.headers():" + request.headers().toString() + "***********************");
        BaseResult result = new BaseResult();
        Response response = null;
        try {
            List lists = Arrays.asList(ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectionSpecs(lists)
                    .sslSocketFactory(createSSLSocketFactory(), new TrustAllCerts())
                    .hostnameVerifier(new TrustAllHostnameVerifier()).build();
            response = client.newCall(request).execute();
            // 获取响应状态码
            int status = response.code();
            // 获取响应接口
            String responseBodyString = response.body().string();
            System.out.println("**********************response.code():" + status + "***********************");
            System.out.println("**********************response.isSuccessful():" + response.isSuccessful() + "***********************");
            if (response.isSuccessful()) {
                result.success(responseBodyString);
            } else {
                result.error(status, "请求失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.error(HttpStatus.STATUS_500);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return result;
    }

//    /**
//     * get
//     * @param url     请求的url
//     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
//     * @return
//     */
//    public static String get(String url, Map<String, String> queries) {
//        StringBuffer sb = getQueryString(url,queries);
//        Request request = new Request.Builder()
//                .url(sb.toString())
//                .build();
//        return execNewCall(request);
//    }

//    /**
//     * post
//     *
//     * @param url    请求的url
//     * @param params post form 提交的参数
//     * @return
//     */
//    public static String postFormParams(String url, Map<String, String> params) {
//        FormBody.Builder builder = new FormBody.Builder();
//        //添加参数
//        if (params != null && params.keySet().size() > 0) {
//            for (String key : params.keySet()) {
//                builder.add(key, params.get(key));
//            }
//        }
//        Request request = new Request.Builder()
//                .url(url)
//                .post(builder.build())
//                .build();
//        return execNewCall(request);
//    }


    /**
     * Post请求发送
     */
    public static BaseResult postJsonParams(String url, Map<String, String> paramsMap, Map<String, String> headersMap) {
        // 添加参数
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        if (paramsMap != null && !paramsMap.isEmpty()) {
            for (String key : paramsMap.keySet()) {
                formBodyBuilder.add(key, paramsMap.get(key));
            }
        }
        // 添加请求头
        Request.Builder builder = new Request.Builder();
        if (headersMap != null && !headersMap.isEmpty()) {
            for (String key : headersMap.keySet()) {
                String value = headersMap.get(key);
                if (StringUtils.isNotBlank(value)) {
                    builder.addHeader(key, value);
                }
            }
        }
        Request request = builder
                .url(url)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .post(formBodyBuilder.build())
                .build();

        return execNewCall(request);
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     */
    public static BaseResult postJsonParams(String url, String jsonParams, Map<String, String> headersMap) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8;"), jsonParams);
        // 添加请求头
        Request.Builder builder = new Request.Builder();
        if (headersMap != null && !headersMap.isEmpty()) {
            for (String key : headersMap.keySet()) {
                String value = headersMap.get(key);
                if (StringUtils.isNotBlank(value)) {
                    builder.addHeader(key, value);
                }
            }
        }
        Request request = builder
                .url(url)
                .post(requestBody)
                .build();

        return execNewCall(request);
    }

//    /**
//     * Post请求发送xml数据....
//     * 参数一：请求Url
//     * 参数二：请求的xmlString
//     * 参数三：请求回调
//     */
//    public static String postXmlParams(String url, String xml) {
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
//        Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();
//        return execNewCall(request);
//    }

    /**
     * 用与HTTPS
     */
    private static class TrustAllCerts implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    /**
     * 用与HTTPS
     */
    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    /**
     * 用与HTTPS
     */
    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssfFactory;
    }

}